//
//  DialerViewController.m
//  HandyDialer
//
//	Developed by Team Synergy
//  Created by Jordan Tseng on 10/29/11.
//  Coders: Jacky Li and Jordan Tseng 
//  Graphic Designer: Derek Fong
//  Developers: Brad Lisson, Derek Fong, Jacky Li, Jeremy Gangoso, Jordan Tseng
//  Copyright HandyDialer 2011. All rights reserved.
//

#import "DialerViewController.h"


@implementation DialerViewController
@synthesize highlightArea;
@synthesize backgroundArea;
@synthesize callNumber;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) 
    {
        // Custom initialization
		rowCounter = 0;
		columnCounter = 0;
		iterationCounter = 0;
		buttonSelect = FALSE;
    }
    return self;
}



- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}



#pragma mark - View lifecycle

- (void)viewDidLoad 
{
	defaults = [NSUserDefaults standardUserDefaults];
	speed = [defaults floatForKey:@"Speed"];
	highlightColor = [defaults stringForKey:@"Highlight"];
	themeColor = [defaults stringForKey:@"Theme"];
    [backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_dialer_default.png"]]];
	[super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated
{
	defaults = [NSUserDefaults standardUserDefaults];
	speed = [defaults floatForKey:@"Speed"];
	highlightColor = [defaults stringForKey:@"Highlight"];
	themeColor = [defaults stringForKey:@"Theme"];
    [backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_dialer_default.png"]]];
	
	if (uniTimer == nil && buttonSelect == FALSE)
		uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
	else if (uniTimer == nil && buttonSelect == TRUE)
		uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(buttonChange) userInfo:nil repeats:YES];
	[super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	if (uniTimer != nil)
	{
		[uniTimer invalidate];
		uniTimer = nil;
	}
	[super viewDidDisappear:animated];
}

- (void)dealloc 
{
	[number release];
	[highlightArea release];
    [super dealloc];
}

// decides which row to highlight
- (void)highlightChange:(NSString *)picture
{
    UIImage *image = [UIImage imageNamed: picture];
    [highlightArea setImage:image];

}

// the process of appending the number in "number"
- (void)appendNum:(int)input
{
	NSString *stringArray[15] = {@"1", @"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"*",@"0",@"#"};
	if (number == NULL)
	{
		number = stringArray[input];
	}
	else
	{
		number = [number stringByAppendingString:stringArray[input]];
	}
    number = [self parseNum:number];

	[number retain];
    callNumber.text = number;
	NSLog(@"%@",number);
	
}

- (NSString *)parseNum:(NSString *)num
{
	// check for special characters
	if ([[num componentsSeparatedByString:@"*"] count] > 1|| [[num componentsSeparatedByString:@"#"] count] > 1)
	{
		return num;
	}
	// only check if appending '-' is needed if number is within valid length
	else if ([num length] > 5 && [num length] < 12)
	{
		// 1- cases
		if ([num hasPrefix:@"1"])
		{
			// check for 1111111s
			if ([[num componentsSeparatedByString:@"1"] count] != [num length]+1)
			{
	
				if ([num length] == 6)
				{
					if ([num characterAtIndex:1] == '-')
					{
						num = [NSString stringWithFormat:@"%@-%@",[num substringToIndex:5],[num substringFromIndex:5]];	 
					}
					else
					{
						num = [NSString stringWithFormat:@"%@-%@-%@",[num substringWithRange:NSMakeRange(0,1)],[num substringWithRange:NSMakeRange(1,3)],[num substringFromIndex:4]];
					}
				}
				else if ([num length] == 11)
				{
					num = [NSString stringWithFormat:@"%@-%@", [num substringToIndex:9], [num substringFromIndex: 9]];
				}
			}
		}
		// no country code
		else
		{
			if ([num length] == 6)
			{
				num = [NSString stringWithFormat:@"%@-%@", [num substringToIndex:3], [num substringFromIndex:3]];
			}
			else if ([num length] == 9)
			{
				num = [NSString stringWithFormat: @"%@-%@", [num substringToIndex:7], [num substringFromIndex:7]];
			}
		}
		return num;
	}
	else
	{
		return num;
	}
}

// Actually switching to that screen 
-(IBAction)switchView:(id)sender
{
        // Does nothing if rowCounter is 0
		if(rowCounter != 0)
		{
            // Checks to see if a button is being selected
			if(buttonSelect == true && columnCounter != 0)
			{
                // Stops timer and reset timeout counter
				[uniTimer invalidate];
				uniTimer = nil;
				iterationCounter = 0;
                
                // Special case for Row 5 to deal with dialing, backspace, clr and back
				if(rowCounter == 5)
				{
					switch (columnCounter)
					{
                        // Call number
						case 1:
						{
							buttonSelect = false;
							if (number != nil)
							{
                                //Deals with dialing numbers lower than three causing errors
                                if(number.length < 3)
                                {
                                    columnCounter = 0;
                                    rowCounter = 0;
                                    buttonSelect = false;
                                    [self rowChange];
                                    uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];  
                                }
                                else
                                {
                                    rowCounter = 0;
                                    columnCounter = 0;
                                    [[UIApplication sharedApplication] openURL:[[NSURL alloc] initWithString:[NSString stringWithFormat:@"tel:%@", number]]];	
                                   // NSLog(@"tel:%@", number);

                                    
                                    NSMutableArray *callLogEntries = [defaults mutableArrayValueForKey:@"CallLog"];
                                    if ([callLogEntries count] > 3)
                                    {
                                        [callLogEntries removeObjectAtIndex:[callLogEntries count]-1];
                                    }
                                    [callLogEntries insertObject:number atIndex:0];
                                    [defaults setObject:callLogEntries forKey:@"CallLog"];
                                    [defaults synchronize];
									[number release];
                                    [self dismissModalViewControllerAnimated:NO];
                                    
                                }
							}
                            // Displays invalid input screen if no number was entered
							else 
							{
								rowCounter = 0;
								columnCounter = 0;
								
								InvalidInputViewController *myViewController = [[InvalidInputViewController alloc]
																	  initWithNibName:@"InvalidInputView"
																	  bundle:nil];
								[self presentModalViewController:myViewController animated:NO];
								;
								[highlightArea setImage:nil];
							}
							break;
						}
                        // Backspace
						case 2:
							if([number length] == 1)
								number = NULL;
							else
                            {
								number = [number substringToIndex:[number length] - 1];
                                if([number hasSuffix:@"-"])
                                {
                                    number = [number substringToIndex:[number length] - 1];
                                }
                            }
							callNumber.text = number;
							columnCounter = 0;
							rowCounter = 0;
							buttonSelect = false;
							[self rowChange];
							uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
							NSLog(@"%@",number);
							break;
                        
                        // Clear
						case 3:
							number = nil;
							callNumber.text =  number;
							columnCounter= 0;
							rowCounter = 0;
							buttonSelect = false;
							[self rowChange];
							uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
							NSLog(@"%@",number);
							break;
                            
                        // Back to main menu
						case 4:
							[self dismissModalViewControllerAnimated:NO];
							[number release];
							break;
					}
				}
                // Append number entered for non-special characters
				else
				{
					[self appendNum:(columnCounter-1+(rowCounter-1)*3)];
					columnCounter = 0;
					rowCounter = 0;
					buttonSelect = false;
					[self rowChange];
					uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
				}
				
			}
            // Case for row select
			else
			{
				[uniTimer invalidate];
				uniTimer = nil;
				buttonSelect = true;
				columnCounter = 0;
				[self buttonChange];
				uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(buttonChange) userInfo:nil repeats:YES];

			}
	}


}

// Decides which row to go to
-(void)rowChange
{
    
	if( rowCounter == 5)
	{
		rowCounter = 0;
	}
	rowCounter += 1;
	NSString *next = highlightColor;
    next = [next stringByAppendingString: @"_dialer_row"];  
	next = [next stringByAppendingString:[NSString stringWithFormat:@"%d", rowCounter]];
	next = [next stringByAppendingString:@".png"];
	[self highlightChange:next];
    
    
}

// decides which button should be displayed next
-(void)buttonChange 
{
    
    
	if (rowCounter == 5)
	{
		if (columnCounter == 4)
		{
			columnCounter = 0;
			iterationCounter += 1;
		}
	}
	else
	{
		if (columnCounter == 3)
		{
			columnCounter = 0;
			iterationCounter += 1;
		}
	}
	if(iterationCounter == 3)
	{
		[uniTimer invalidate];
		uniTimer = nil;
		iterationCounter = 0;
		columnCounter = 0;
		rowCounter = 0;
		buttonSelect = false;
		[self rowChange];
		uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
		
	}
	else
	{
		columnCounter += 1;
		NSString *next = highlightColor;
		next = [next stringByAppendingString:@"_dialer_"];  
		next = [next stringByAppendingString:[NSString stringWithFormat:@"%d", columnCounter+(rowCounter-1)*3]];
		next = [next stringByAppendingString:@".png"];
		[self highlightChange:next];
	}
    
}

@end

